package world.hezi.utils;

import net.mamoe.mirai.contact.Contact;
import net.mamoe.mirai.message.data.Image;
import net.mamoe.mirai.message.data.Message;
import net.mamoe.mirai.utils.ExternalResource;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.ibatis.session.SqlSession;
import redis.clients.jedis.Jedis;
import world.hezi.bot.BeatsaverBot;
import world.hezi.callback.LongPicturesCallBack;
import world.hezi.callback.TencentPicturesHttpCallback;
import world.hezi.entity.PicInfo;
import world.hezi.handlers.HPicturesHandlers;
import world.hezi.http.GetPicturesCache;
import world.hezi.mapper.PicInfoMapper;
import world.hezi.mapper.UserXpMapper;
import world.hezi.pools.MybatisPools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PicturesUtil {
    public static List<Image> getRandomPicture(Long sender, Contact contact, Integer num, UserXpMapper userXpMapper, Jedis jedis){
        List<String> userXp = userXpMapper.getUserXp(sender);
        if (userXp==null||userXp.size()==0)
            return new ArrayList<>();
        String[] strings = new String[userXp.size()];
        for (int i = 0; i < userXp.size(); i++) {
            strings[i] = userXp.get(i);
        }
        String name = sender+":"+System.currentTimeMillis();
        jedis.sunionstore(name,strings);
        Set<String> spop = jedis.spop(name, num);
        jedis.del(name);
        List<Image> re = new ArrayList<>();
        for (String s : spop) {
            try(ExternalResource externalResource = ExternalResource.create(new File(BeatsaverBot.PIC_PATH+s))) {
                Image image = contact.uploadImage(externalResource);
                re.add(image);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return re;
    }
    public static Image getHelpImg(Contact contact){
        return uploadAndGetImage(new File(BeatsaverBot.PIC_PATH+"/help.png"),contact);
    }
    public static Image uploadAndGetImage(byte[] bytes,Contact contact) throws IOException {
        String name = BeatsaverBot.PIC_PATH+ UUID.randomUUID()+".png";
        FileOutputStream fileOutputStream = new FileOutputStream(name);
        fileOutputStream.write(bytes);
        fileOutputStream.close();
        try(ExternalResource externalResource = ExternalResource.create(new File(name))) {
            return contact.uploadImage(externalResource);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static Image uploadAndGetImage(File file,Contact contact) {
        try(ExternalResource externalResource = ExternalResource.create(file)) {
            return contact.uploadImage(externalResource);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static List<String> getIdsList(Message message){
        String str = message.toString();
        int t;
        //
        List<String> ids = new ArrayList<>();
        while ((t = str.indexOf("[mirai:image:"))>=0){
            str = str.substring(t+13);
            ids.add(str.substring(0, str.indexOf(",")));
        }
        return ids;
    }
    public static int getNumber(String str){
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return Integer.parseInt(m.replaceAll("").trim());
    }
    public static int getType(String message){
        if (message.indexOf("色图")==0
                ||message.equals("来点色图")
                ||message.equals("sese")
                ||message.equals("色色")
                ||message.equals("涩涩")
                ||message.equals("来点图")
                ||message.equals("来张涩图")
                ||message.equals("来份涩图")
                ||message.equals("来一份涩图")
                ||message.equals("来1份涩图")
                ||message.equals("来点涩图")
                ||message.equals("涩图")
                ||message.equals("美图")
                ||message.equals("来点美图"))
            return 0;
        else if (message.indexOf("添加图片:")==0
                ||message.indexOf("添加色图:")==0
                ||message.indexOf("添加涩图:")==0
                ||message.indexOf("添加美图:")==0
                ||message.indexOf("上传色图:")==0
                ||message.indexOf("上传涩图:")==0
                ||message.indexOf("上传图片:")==0
                ||message.indexOf("上传:")==0
                ||message.indexOf("添加:")==0
                ||message.indexOf("添加色图：")==0
                ||message.indexOf("添加涩图：")==0
                ||message.indexOf("添加美图：")==0
                ||message.indexOf("上传色图：")==0
                ||message.indexOf("上传涩图：")==0
                ||message.indexOf("上传图片：")==0
                ||message.indexOf("上传：")==0
                ||message.indexOf("添加：")==0
                ||message.indexOf("添加图片：")==0){
            return 10;
        }
        else if (message.indexOf("添加xp:")==0
                ||message.indexOf("添加XP:")==0
                ||message.indexOf("添加xp：")==0
                ||message.indexOf("添加XP：")==0
                ||message.indexOf("新增xp:")==0
                ||message.indexOf("新增XP:")==0
                ||message.indexOf("新增xp：")==0
                ||message.indexOf("新增XP：")==0
                ){
            return 20;
        }else if (message.indexOf("删除xp:")==0
                ||message.indexOf("删除XP:")==0
                ||message.indexOf("删除xp：")==0
                ||message.indexOf("删除XP：")==0
        ) return 21;
        else if (message.indexOf("我的xp")==0
                ||message.indexOf("我的XP")==0
        ) return 22;
        else if (message.indexOf("新增全局xp:")==0
                ||message.indexOf("新增全局XP:")==0
                ||message.indexOf("新增全局xp：")==0
                ||message.indexOf("新增tag:")==0
                ||message.indexOf("新增图片tag:")==0
                ||message.indexOf("添加tag:")==0
                ||message.indexOf("添加图片tag:")==0
                ||message.indexOf("新增tag：")==0
                ||message.indexOf("新增图片tag：")==0
                ||message.indexOf("添加tag：")==0
                ||message.indexOf("添加图片tag：")==0
                ||message.indexOf("新增图片标签:")==0
                ||message.indexOf("新增标签：")==0
                ||message.indexOf("新增全局XP：")==0
                ||message.indexOf("添加全局XP:")==0
                ||message.indexOf("添加全局xp：")==0
                ||message.indexOf("添加全局XP：")==0
                ||message.indexOf("添加全局xp:")==0
        ) return 23;
        else if (message.indexOf("查看全局xp")==0
                ||message.indexOf("查看全局XP")==0
                ||message.indexOf("全局xp")==0
                ||message.indexOf("全局XP")==0
                ||message.indexOf("图片tag")==0
                ||message.indexOf("图片标签")==0
                ||message.indexOf("全局图片tag")==0
                ||message.indexOf("全局图片标签")==0
        ) return 24;
        else if (message.equals("!help")
                ||message.equals("！help")
                ||message.equals("!!help")
                ||message.equals("！！help")
        ) return 10000;
        Pattern pattern = Pattern.compile("来[0-9]+张涩图");
        Pattern pattern1 = Pattern.compile("来[0-9]+张色图");
        Pattern pattern2 = Pattern.compile("来[0-9]+张美图");
        Pattern pattern3 = Pattern.compile("来[0-9]+张美图");
        Pattern pattern4 = Pattern.compile("来[0-9]+张图");
        message = HPicturesHandlers.getPureNumber(message);
        if (pattern.matcher(message).find()
                ||pattern1.matcher(message).find()
                ||pattern2.matcher(message).find()
                ||pattern3.matcher(message).find()
                ||pattern4.matcher(message).find()){
            return 100;
        }
        return -1;
    }
    public static int checkAndSave(PicInfoMapper picInfoMapper,Jedis jedis, Long sender,Message message) {
        String t;
        if (jedis.exists(t = "add:"+sender)){
            List<String> idsList = getIdsList(message);
            String[] strings = jedis.get(t).split(":");
            if (idsList.size()==0){
                jedis.del(t);
                return Integer.parseInt(strings[1]);
            }
            jedis.set(t,strings[0]+":"+(Integer.parseInt(strings[1])+idsList.size()));
            for (String s : idsList) {
                PicInfo picInfo = new PicInfo();
                picInfo.setUpdateUser(sender);
                picInfo.setUuid(s);
                picInfo.setType(0);
                picInfo.setTag(strings[0]);
                picInfo.setUpdateTime(System.currentTimeMillis());
                GetPicturesCache.saveCache(s,picInfoMapper,picInfo);
                jedis.sadd(picInfo.getTag(),picInfo.getUuid());
            }
            return -1;
        }
        return -2;
    }
    public static File saveAndGetFile(String uuid){
        String url = Image.queryUrl(Image.fromId(uuid));
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        CountDownLatch countDownLatch = new CountDownLatch(1);
        call.enqueue(new LongPicturesCallBack(countDownLatch, uuid));
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        File file = new File("C:\\Users\\65134\\Desktop\\long\\test\\" + uuid);
        if (file.exists()){
            return file;
        }else {
            return null;
        }
    }
}
